﻿(function() {
    "use strict";
    var app = angular.module("bookStore", ["ngRoute", "ngTable", "appDirectives"], function ($httpProvider) {
        $httpProvider.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";
    });

    app.service("BookStoreService", function ($http) {
        this.getBook = function (id) {
            return $http.get("/book/get/" + id);
        };

        this.getBookList = function() {
            return $http.get("/book/list");
        };

        this.addBook = function (book) {
            if ($.isArray(book)) {
                return $http.post("/book/add", book);
            }
            return $http.post("/book/add", [book]);
        };

        this.modifyBook = function (book) {
            return $http.put("/book/modify", book);
        };

        this.removeBook = function(book) {
            return $http.delete("/book/delete/" + book.id);
        };
    });

    app.service("CoverUpload", ["$http", function ($http) {
        this.upload = function(bookId, image, url){
            var data = new FormData();
            data.append("file", image);
            return $http.post(url + "?book=" + bookId, data, {
                transformRequest: angular.identity,
                headers: { "Content-Type": undefined }
            });
        }
    }]);

    app.controller("MasterController", function ($scope, $rootScope, BookStoreService) {
        this.pushData = function () {
            var $btn = $("#dataPusher").button("loading");
            BookStoreService.addBook([
                {
                    id:1,
                    title: "The Way of All Flesh",
                    authors: [{ name: "Samuel", lastName: "Butler" }],
                    pages: 280,
                    publisher: "Farrar, Straus and Giroux",
                    isbn: "978-0-37-428682-8",
                    year: 1903
                },
                {
                    id: 2,
                    title: "Stainless Steel Rat",
                    authors: [
                        { name: "Harry", lastName: "Harrison" },
                        { name: "Harry", lastName: "Harrison (Delete It)" }],
                    pages: 496,
                    publisher: "Tor Books",
                    isbn: "978-0-76-530278-6",
                    year: 1985
                },
                {
                    id: 3,
                    title: "Deathworld",
                    authors: [{ name: "Harry", lastName: "Harrison" }],
                    pages: 496,
                    publisher: "BenBella Books",
                    isbn: "978-1-93-210041-9",
                    year: 1960
                }
            ]).then(function(res) {
                $btn.button("reset");
                $scope.$broadcast("dataPushed");
            } , function() {
                $btn.button("reset");
            });
        };
    });

    app.controller("BookEditorController",
        function($scope, BookStoreService, CoverUpload) {
            var _backup = {};
            var self = this,
                isNew = false;

            $scope.book = {};
            $scope.isNew = true;
            $scope.bookCover;

            $scope.newAuthor = { Name: "John", LastName: "Doe" };
            $scope.isbnStandard = /^(?=.{17}$)97(?:8|9)([ -])\d{1,5}\1\d{1,7}\1\d{1,6}\1\d$/;

            $scope.$on("editBook", function (e, book) {
                isNew = false;
                $scope.bookCover = undefined;
                $scope.book = book;
                angular.copy(book, _backup);
            });

            $scope.$on("addBook", function (e) {
                isNew = true;
                $scope.book = {};
            });

            this.rollback = function () {
                if (!isNew) angular.copy(_backup, $scope.book);
                $scope.$broadcast("bookEdited");
            };

            $scope.commit = function () {
                BookStoreService[!isNew ? "modifyBook" : "addBook"]($scope.book).then(function (res) {
                    if ($scope.bookCover) {
                        CoverUpload.upload(res.data[0], $scope.bookCover, "/book/image").then(function () {
                            $(".modal").modal("hide");
                            $scope.bookCover = undefined;
                            $scope.$emit("refreshData");
                            $scope.$broadcast("bookEdited");
                        });
                    } else {
                        $(".modal").modal("hide");
                    }
                });
            };

            $scope.commitAuthor = function () {
                $scope.book.authors = $scope.book.authors || [];
                $scope.book.authors.push($scope.newAuthor);
                self.editAuthors(false);
            };

            this.editAuthors = function(flag) {
                $scope.authorsEdit = flag;
                if (flag) {
                    $scope.newAuthor = {};
                } else {
                    $scope.newAuthor = { Name: "John", LastNAme: "Doe" };
                }
            };
        });

    app.config([
        "$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
            $routeProvider
                .when("/", {
                    templateUrl: "default/workspace"
                })
                .when("/features", {
                    templateUrl: "default/features"
                })
                .when("/contacts", {
                    templateUrl: "default/contacts"
                });

            // $locationProvider.html5Mode(true);
        }
    ]);
})();